package com.szholly.plug.form.directive;

import static freemarker.template.ObjectWrapper.DEFAULT_WRAPPER;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;

import org.springframework.stereotype.Component;

import com.szholly.utils.freemarker.directive.DirectiveUtils;
import com.szholly.utils.freemarker.directive.IDirective;
import com.szholly.utils.spring.springmvc.route.FunctionInfo;
import com.szholly.utils.util.TreeDataNode;
import com.szholly.data.common.util.TablesUtils;

import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;

/**
 * 定义获取数据表内容的标签
 */
@Component("directive_tables")
public class TablesDirective implements TemplateDirectiveModel, IDirective {

	/**
	 * 是否添加空行
	 */
	private static String PARA_ADDSPACEITEM = "addSpaceItem";

	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Override
	public void execute(Environment env, Map params, TemplateModel[] arg2,
			TemplateDirectiveBody body) throws TemplateException, IOException {
		Map<String, TemplateModel> paramWrap = new HashMap<String, TemplateModel>(
				params);

		List<TreeDataNode> result = TablesUtils.getTables();

		Boolean addSpaceItem = DirectiveUtils.getBool(PARA_ADDSPACEITEM, params);
		if (addSpaceItem !=null && addSpaceItem == true) {
			TreeDataNode spaceNode = new TreeDataNode();
			spaceNode.setid("");
			spaceNode.setText("");
			spaceNode.setState("open");
			if (result == null) {
				result = new ArrayList<TreeDataNode>();
			}
			result.add(0, spaceNode);
		}

		JSONArray arrayObject = JSONArray.fromObject(result);
		String returnValue = arrayObject.toString();

		paramWrap.put("data", DEFAULT_WRAPPER.wrap(returnValue));

		Map<String, TemplateModel> origMap = DirectiveUtils
				.addParamsToVariable(env, paramWrap);
		body.render(env.getOut());
		DirectiveUtils.removeParamsFromVariable(env, paramWrap, origMap);
	}
	
	@Override
	public FunctionInfo getFunctionInfo() {
		String paraInfo = "addSpaceItem：是否添加空行数据<br/>调用示例：<@tables addSpaceItem='true' />";
		FunctionInfo info = new FunctionInfo("tables", 1, "系统构建",
				"获取所有表信息数据", paraInfo);
		return info;
	}
}